package com.jing.ListAdapter.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.jing.ListAdapter.R;
import com.jing.ListAdapter.entity.Student;

import java.util.List;

public class MyListAdapter extends BaseAdapter {
    Context context;
    List<Student> students;

    public MyListAdapter(Context context, List<Student> students){
        this.context=context;
        this.students=students;
    }
    @Override
    public int getCount() {
        return students.size();
    }

    @Override
    public Object getItem(int position) {
        return students.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //创建ViewHolder的对象。
        ViewHolder viewHolder = null;
        //获得Item位置上的数据。
        Student student = students.get(position);
        if(convertView == null){
            convertView = LayoutInflater.from(context).inflate(R.layout.layout_student_list, parent, false);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.name.setText(student.getName());
        viewHolder.age.setText(String.valueOf(student.getAge()));
        viewHolder.sex.setText(student.getSex());

        return convertView;
    }

    static class ViewHolder{
        private final TextView name;
        private final TextView age;
        private final TextView sex;

        public ViewHolder(View itemView){
            name = itemView.findViewById(R.id.name);
            age = itemView.findViewById(R.id.age);
            sex = itemView.findViewById(R.id.sex);
        }
    }
}